package top.yzhelp.enjoyinformation.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import top.yzhelp.enjoyinformation.controller.res.Result;
import top.yzhelp.enjoyinformation.model.Apply;
import top.yzhelp.enjoyinformation.model.Book;
import top.yzhelp.enjoyinformation.service.ApplyService;
import top.yzhelp.enjoyinformation.service.BookService;
import top.yzhelp.enjoyinformation.shiro.ShiroRealm;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 码之泪殇 GitHub: https://github.com/gongsir0630
 * @date 2021/3/26 18:12
 * 你的指尖,拥有改变世界的力量
 * @description 申请消息接口
 */
@RestController
@RequestMapping("apply")
@Slf4j
@RequiresAuthentication
public class ApplyController {

    @Resource
    private ApplyService applyService;
    @Resource
    private BookService bookService;

    private String getUserId() {
        return ShiroRealm.getUserId();
    }

    /**
     * 查看我的未读消息
     * @return 所有未读消息
     */
    @GetMapping("list")
    public ResponseEntity<Result<List<Apply>>> getList() {
        QueryWrapper<Book> bookQueryWrapper = new QueryWrapper<>();
        bookQueryWrapper.eq("user_id",getUserId());
        // 所有我发布的book
        List<Integer> ids = bookService.list(bookQueryWrapper).stream().map(Book::getId).collect(Collectors.toList());
        QueryWrapper<Apply> applyQueryWrapper = new QueryWrapper<>();
        // 我的未读
        applyQueryWrapper.in("book_id",ids).eq("status",false).orderByDesc("id");
        List<Apply> applies = applyService.list(applyQueryWrapper);
        return new ResponseEntity<>(Result.success(applies), HttpStatus.OK);
    }

    /**
     * 消息处理
     * @param id 消息 id
     * @return apply
     */
    @PostMapping("/{id}")
    public ResponseEntity<Result<Apply>> readById(@PathVariable("id") int id) {
        // 1. 修改消息表
        Apply apply = applyService.getById(id);
        apply.setStatus("true");
        // 消息设置为已查看
        applyService.updateById(apply);

        // 2. 修改二手书表
        String fromUser = apply.getFromUser();
        // 申请查看的二手书信息
        Book book = bookService.getById(apply.getBookId());
        List<String> whiteList = book.getWhiteList() != null
            ? Arrays.stream(book.getWhiteList().split(",")).collect(Collectors.toList())
            : new ArrayList<>();
        // 加入白名单
        if (!whiteList.contains(fromUser)) {
            whiteList.add(fromUser);
        }
        book.setWhiteList(String.join(",",whiteList));
        bookService.updateById(book);
        return new ResponseEntity<>(Result.success(apply),HttpStatus.OK);
    }
}
